import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/dto/assessment_question_record.body.dart';
import 'package:ichinesereader/models/assessment/assessmentQueryDto.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordDto.dart';
import 'package:ichinesereader/models/assessment/questionGroup.dart';
import 'package:ichinesereader/models/assessment/assessmentDto.dart';
import 'package:ichinesereader/models/assessment/questionResult.dart';
import 'package:ichinesereader/utils/log.dart';

class AssessmentServiceProvider extends GetConnect {
  AssessmentServiceProvider() {
    httpClient.addResponseModifier((request, response) {
      if (response.statusCode == 403) {
        Log.debug('${request.url} 403 error');
        if (!Get.isSnackbarOpen) {
          Get.snackbar(
            'Message'.tr,
            'You have been logged out due to inactivity or security reasons.'
                .tr,
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Color(0xff23c6c8),
            colorText: Color(0xffd8ffff),
          );
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else if (response.statusCode == 401) {
        Log.debug('${request.url} unauthorized access');
        if (!Get.isSnackbarOpen) {
          Get.snackbar('Message'.tr, 'Unauthorized access'.tr,
              backgroundColor: Color(0xff23c6c8),
              colorText: Color(0xffd8ffff),
              snackPosition: SnackPosition.BOTTOM);
        }
        if (EasyLoading.isShow) {
          EasyLoading.dismiss();
        }
        if (Get.currentRoute != '/login') {
          return Get.offAllNamed('/login');
        }
      } else {
        Log.debug(response.request?.url.toString());
        return response;
      }
    });
    httpClient.maxAuthRetries = 2;
    httpClient.timeout = Duration(seconds: 30);
  }

  Future<dynamic> getQuizBooks(
      String? limit, String? page, String? type) async {
    if (limit == null) limit = '0';
    if (page == null) page = '0';
    if (type == null) type = 'AP';
    type = 'type=AP&type=SOCIAL_STUDIES';
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/record/list?$type&limit=$limit&page=$page&sortField=commitTime',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//https://superbe.migration.ichinesereader.com/superadmin/question/group?page=0&sortField=level&limit=24&type=IBDP_AB,IBDP_BSL,IBDP_BHL&kind=SPEAKING
  Future<dynamic> getAssessmentBooks(
      String? limit, String? page, String? type, String? kind) async {
    if (limit == null) limit = '0';
    if (page == null) page = '0';
    if (type == null) type = 'RUNNING_RECORD';
    if (kind == null) kind = '';
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    // Uri url = Uri.parse(
    //     '${Constants.BaseAPISuper}superadmin/question/record/list?type=$type&limit=$limit&page=$page&sortField=commitTime');
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/group?type=$type&limit=$limit&page=$page&sortField=level&kind=$kind',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//https://superbe.migration.ichinesereader.com/superadmin/question/record/19070715-0622-4282-91eb-b975018abb66
// assessmentQuestionsResult
  Future<dynamic> getQuestionsByAssessmentId(String assessmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var _userName = box.get(CacheManagerKey['username'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/record/$assessmentId?userName=$_userName',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> submitAssessmentGrade(String dtoJson) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/examination/test',
      dtoJson,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
      //  body: jsonEncode({})
    );
    return response;
  }

  Future<dynamic> getAssessmentGrade(String recordId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/examination/test/$recordId';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<String?> getArticleInfo(String jsonUrl) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(jsonUrl, headers: <String, String>{
      'authtoken': _authtoken,
      'content-type': 'application/json;charset=UTF-8'
    });
    return response.bodyString;
  }

  Future<String?> getArticleTextInfo(String bookId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
        'https://resources.ichinesereader.com/media/runingrecords/$bookId/ttext.txt',
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        });
    return response.bodyString;
  }

  Future<dynamic> getMineAssessment(Map param) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    Map<String, String> query = {};
    param.forEach((key, value) {
      query[key] = value.toString();
    });
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/assessment/mine',
      param,
      query: query,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getMineAssessmentCount() async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/assessment/mine/count',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getAllAssessmentsByClass(
      String cid, AssessmentQueryDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/assessment/$cid',
      assessmentQueryDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//{"status":1000,"message":"create assessment success","result":{"id":"29808a1a-7e30-4933-967b-c182a53529d6"}}
  Future<dynamic> createAssessment(
      AssessmentDto dto, String? assessmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    if (assessmentId != '' && assessmentId != null) {
      // edit
      final response = await put(
        '${Constants.BaseAPISuper}superadmin/assessment',
        assessmentDtoToJson(dto),
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
      );
      return response;
    } else {
      // create
      final response = await post(
        '${Constants.BaseAPISuper}superadmin/assessment',
        assessmentDtoToJson(dto),
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        },
      );
      return response;
    }
  }

  Future<dynamic> updateAssessment(AssessmentDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/assessment',
      assessmentDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> deleteAssessmentById(String id) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await delete(
      '${Constants.BaseAPISuper}superadmin/assessment/$id',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//https://superbe.migration.ichinesereader.com/superadmin/question/record/19070715-0622-4282-91eb-b975018abb66
// assessmentQuestionsResult
  Future<dynamic> getQuestionsById(String assessmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    var _userName = box.get(CacheManagerKey['username'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/record/$assessmentId?userName=$_userName',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getAssessmentRecords(
      String classId, String limit, String page) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    if (limit == '') limit = '0';
    if (page == '') page = '0';
    String url =
        '${Constants.BaseAPISuper}superadmin/assessment/report/$classId?limit=$limit&page=$page&sortField=-submittedTime';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//https://superbe.ichinesereader.com/superadmin/question/record/info/c99e18c1-5d11-492e-9d7f-08e5f005abcf
  ///assessmentQuestionsRecordResult
  Future<dynamic> getAssessmentRecordDetails(String recordId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String url =
        '${Constants.BaseAPISuper}superadmin/question/record/info/$recordId';
    final response = await get(
      url,
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//questiongroups result
  Future<dynamic> getQuestionGroups(
      String? limit, String? page, String? type, String? kind) async {
    if (limit == null || limit == '') limit = '0';
    if (page == null || page == '') page = '0';
    if (type == null || type == '') type = 'EVALUATION';
    if (kind == null || kind == '') kind = 'TEST';
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/group?type=$type&limit=$limit&page=$page&kind=$kind',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//questiongroup result
  Future<dynamic> getQuestionGroupByGroupId(String? groupId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/groupById/$groupId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

//questiongroup result
  Future<dynamic> getQuestionGroupByBookId(String? bookId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/groupByBookId/$bookId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getQuestionGroupByBookCode(
      String bookCode, bool? simplified, bool? mandarin) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String isSimplified = 'true';
    String isMandarin = 'true';
    isSimplified = simplified == false ? 'false' : 'true';
    isMandarin = mandarin == false ? 'false' : 'true';

    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/fixed?bookId=$bookCode&simplified=$isSimplified&mandarin=$isMandarin',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getQuickReviewQuestionGroupByBookCode(
      String bookCode, bool simplified, bool mandarin) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    //String bookId = '$bookCode-review';
    // for test
    //String bookId = 'DE0046-review';
    String isSimplified = 'true';
    String isMandarin = 'true';
    isSimplified = simplified == false ? 'false' : 'true';
    isMandarin = mandarin == false ? 'false' : 'true';
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/fixed?bookId=$bookCode&simplified=$isSimplified&mandarin=$isMandarin',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> getGramamrQuestionGroupByBookCode(
      String bookCode, String simplified, String mandarin) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    String isSimplified = 'true';
    String isMandarin = 'true';
    isSimplified = simplified == 'Simplified' ? 'true' : 'false';
    isMandarin = mandarin == 'Mandarin' ? 'true' : 'false';
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/knowledge/book/$bookCode?language=English&simplified=$isSimplified&mandarin=$isMandarin',
      headers: <String, String>{"authtoken": _authtoken},
    );
    return response;
  }

  Future<dynamic> createQuestion(QuestionDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question',
      questionDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> updateQuestion(QuestionDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/question',
      questionDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> createQuestionGroup(QuestionGroupDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question/group',
      questionGroupDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<dynamic> updateQuestionGroup(QuestionGroupDto dto) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await put(
      '${Constants.BaseAPISuper}superadmin/question/group',
      questionGroupDtoToJson(dto),
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  //questionResult
  Future<dynamic> getQuestionById(String? questionId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPISuper}superadmin/question/$questionId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response;
  }

  Future<AssessmentResult?> getAssessment(String assessmentId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
        '${Constants.BaseAPISuper}superadmin/question/record/$assessmentId',
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        });
    return AssessmentResult.fromJson(
        json.decode(response.bodyString!)['result']);
  }

  Future<String?> getExaminationReportHtml(String recordId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
        '${Constants.BaseAPISuper}superadmin/examination/report/html/$recordId',
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        });
    return response.bodyString;
  }

  Future<AssessmentResult?> getAssessmentByStudentName(
      String assessmentId, String studentName) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
        '${Constants.BaseAPISuper}superadmin/question/record/$assessmentId?userName=$studentName',
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        });
    return AssessmentResult.fromJson(
        json.decode(response.bodyString!)['result']);
  }

  Future<QuestionPart?> getPlacementQuizzes(Map param) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
        '${Constants.BaseAPISuper}superadmin/question/assessment/basicSurvey?optionKey=${param['optionKey']}&simplified=${param['simplified']}&mandarin=${param['mandarin']}',
        headers: <String, String>{
          'authtoken': _authtoken,
          'content-type': 'application/json;charset=UTF-8'
        });
    String dataJson = response.bodyString!;

    return QuestionPart.fromJson(json.decode(dataJson.replaceFirst(
        '\"result\":{\"list\":[', '\"result\":{\"questions\":['))['result']);
  }

  Future<String?> postSubmitPlacementRecord(Map param) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question/assessment/pretest',
      param,
      decoder: (data) {
        return data;
      },
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return response.bodyString!;
  }

  AssessmentResult? dealQuizJsonData(String dataJson) {
    String dealJson =
        "{\"list\":[{\"questions\":[{\"question\":" + dataJson + "}]}]}";
    return AssessmentResult.fromJson(json.decode(dealJson));
  }

  Future<void> postQuestionRecord(QuestionRecordBody body) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question/record',
      body.toJson(),
      decoder: (data) {
        return data;
      },
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    Log.debug(response.bodyString);
  }

  Future<void> postSubmitReportRecord(QuestionRecordBody body) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question/assessment/test',
      body.toJson(),
      decoder: (data) {
        return data;
      },
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    Log.debug(response.bodyString);
  }

  Future<dynamic> postSubmitReportRecordNew(QuestionRecordBodyNew body) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question/assessment/test',
      body.toJson(),
      decoder: (data) {
        return data;
      },
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    Log.debug(response.bodyString);
    return response;
  }

  Future<dynamic> submitQuestionRecord(AssessmentRecordDto body) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question/assessment/test',
      body.toJson(),
      decoder: (data) {
        return data;
      },
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    Log.debug(response.bodyString);
    return response;
  }

  Future<dynamic> saveQuestionRecord(AssessmentRecordDto body) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await post(
      '${Constants.BaseAPISuper}superadmin/question/record',
      body.toJson(),
      decoder: (data) {
        return data;
      },
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    Log.debug(response.bodyString);
    return response;
  }

  Future<String> getQuestionRecordingByFileId(String fileId) async {
    final box = Hive.box('appconfig');
    var _authtoken = box.get(CacheManagerKey['authtoken'].toString());
    final response = await get(
      '${Constants.BaseAPI}studentmanager/location/file/$fileId',
      headers: <String, String>{
        'authtoken': _authtoken,
        'content-type': 'application/json;charset=UTF-8'
      },
    );
    return json.decode(response.bodyString!)['location'].toString();
  }
}
